package com.sk.waste.app.fragments

import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.EditText
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.tabs.TabLayout
import com.lc.smc.lib.interfaces.LCInterface
import com.lc.smc.lib.utils.LCBaseUtil
import com.lc.smc.lib.utils.LCSPUtil
import com.lc.smc.lib.views.pulllayout.SKPullRefresh
import com.lc.smc.lib.views.pulllayout.SKPullRefreshLayout
import com.sk.waste.app.R
import com.sk.waste.app.adapters.MarketAdapter
import com.sk.waste.app.application.MyApplication
import com.sk.waste.app.bases.BaseFragment
import com.sk.waste.app.config.AppConfig
import com.sk.waste.app.config.NetWorkConfig
import com.sk.waste.app.interfaces.SKInterface
import com.sk.waste.app.models.MarketModel
import com.sk.waste.app.models.TenderModel
import com.sk.waste.app.models.TypeModel
import com.sk.waste.app.utils.OkHttpUtil
import okhttp3.Call
import org.json.JSONObject
import java.io.IOException
import java.util.Arrays

/**
 *  @time 2025/4/25  10:02
 *  @desc 行情报价首页
 */
class MarketFragment : BaseFragment() {

    private lateinit var ettSearch: EditText
    private lateinit var bttSearch: Button
    private lateinit var tabLayout: TabLayout
    private lateinit var pullRefreshLayout: SKPullRefreshLayout
    private lateinit var recyclerView: RecyclerView

    private var currentPage = 1
    private var searchStr = ""
    private var currentType = ""
    private val PAGE_SIZE = 15

    private var labList = ArrayList<TypeModel>()
    private var marketList = ArrayList<MarketModel>()
    private lateinit var marketAdapter: MarketAdapter
    val userinfo = MyApplication.instance.getUserInfo()

    override fun onCreate(savedInstanceState: Bundle?) {
        setContentView(R.layout.fragment_second)
        super.onCreate(savedInstanceState)
    }

    override fun findView() {
        ettSearch = findViewById(R.id.view_search_text) as EditText
        bttSearch = findViewById(R.id.view_search_butt) as Button
        tabLayout = findViewById(R.id.fg_market_tablayout) as TabLayout
        pullRefreshLayout = findViewById(R.id.fg_market_swipeRefreshLayout) as SKPullRefreshLayout
        recyclerView = findViewById(R.id.fg_market_recyclerview) as RecyclerView
    }

    override fun setListener() {
//        pullRefreshLayout.initView(recyclerView,skPullRefreshLayout)
        pullRefreshLayout.onStartListener = refreshListener
        pullRefreshLayout.onStartListener.onStartRefresh(pullRefreshLayout)

//        judgeVip()

        recyclerView.layoutManager = LinearLayoutManager(mContext)
        marketAdapter = MarketAdapter(mContext!!, 1, marketList, null)
        recyclerView.adapter = marketAdapter
        getTypeList()
        bttSearch.setOnClickListener {
            currentPage = 1
            marketList.clear()
            hideKeyboard()
            searchStr = ettSearch.text.toString()
            getMarketList()
        }
        ettSearch.setOnEditorActionListener { v, actionId, event -> // 在这里处理搜 索逻辑
            // 返回 true 表示你已经处理了这个事件
            currentPage = 1
            marketList.clear()
            searchStr = ettSearch.text.toString()
            getMarketList()
            true
        }
    }

    /**
     *  @time 2025/4/25  14:37
     *  @desc 初始化tablayout
     */
    private fun initTablayout() {
        for (item in labList) {
            val tabItem = tabLayout.newTab().apply { text = item.name }
            tabLayout.addTab(tabItem)
        }

        tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab) {
                currentPage = 1
                searchStr = ""
                currentType = labList[tab.position].code
                getMarketList()
            }

            override fun onTabUnselected(tab: TabLayout.Tab) {
            }

            override fun onTabReselected(tab: TabLayout.Tab) {}
        })
    }

    private val refreshListener = object : SKPullRefresh.OnStartListener {
        override fun onStartRefresh(p0: SKPullRefresh?) {
            currentPage = 1
            getMarketList()
        }

        override fun onStartLoadmore(p0: SKPullRefresh?) {
            if (userinfo!!.isVip()) {
                currentPage++
                getMarketList()
            } else {
                currentPage = 1
                pullRefreshLayout.loadmoreSuccess()
            }
        }
    }


    /**
     *  @time 2024/5/7  11:29
     *  @desc 行情分类
     *  @param url
     */
    private fun getTypeList() {

        val url = NetWorkConfig.NET_URL_ROOT + NetWorkConfig.NET_URL_MAIN_MARKETLIST
        val token = LCSPUtil[mContext!!, AppConfig.SP_ACCESS_TOKEN]
        val httpUtil = OkHttpUtil()
        httpUtil.httpRequestGet(url, token, object : LCInterface.LcCallBackListener {
            override fun onFailure(call: Call, e: IOException) {
                LCBaseUtil.showToast(context, "获取失败，" + e.message)
            }

            @Throws(IOException::class)
            override fun onSuccess(call: Call, response: String) {
                try {
                    val jsonObject = JSONObject(response)
                    val success = jsonObject.getBoolean("success")
                    val msg = jsonObject.getString("message")
                    val code = jsonObject.getInt("code")
                    val data = jsonObject.getJSONArray("data")
                    labList.clear()
                    val item = TypeModel().apply { name = "全部" }
                    labList.add(item)
                    if (success) {
                        for (index in 0 until data.length()) {
                            val item = TypeModel().apply { getModelInfo(data.getJSONObject(index)) }
                            labList.add(item)
                        }
                        activity!!.runOnUiThread { initTablayout() }
//                        LCLogger.d(TAG, "获取成功！,返回信息：$jsonObject")
                    } else {
                        LCBaseUtil.showToast(context, "获取失败，$msg")
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    LCBaseUtil.showToast(context, "获取失败，" + e.message)
                }
            }
        })
    }


    /**
     *  @time 2024/5/7  11:29
     *  @desc 行情
     *  @param url
     */
    private fun getMarketList() {
        val url = NetWorkConfig.NET_URL_ROOT + NetWorkConfig.NET_URL_MAIN_MARKET
        val token = LCSPUtil[mContext!!, AppConfig.SP_ACCESS_TOKEN]
        val params = JSONObject()
        params.put("pageSize", PAGE_SIZE)
        params.put("pageNo", currentPage)
        params.put("marketTypeCodes", currentType)
        params.put("productName", searchStr)

        val httpUtil = OkHttpUtil()
        httpUtil.httpRequest(url, token, params.toString(), object : LCInterface.LcCallBackListener {
            override fun onFailure(call: Call, e: IOException) {
                freshOrLoadFaild()
                LCBaseUtil.showToast(context, "获取失败，" + e.message)
            }

            @Throws(IOException::class)
            override fun onSuccess(call: Call, response: String) {
                try {
                    val jsonObject = JSONObject(response)
                    val success = jsonObject.getBoolean("success")
                    val msg = jsonObject.getString("message")
                    val code = jsonObject.getInt("code")
                    val data = jsonObject.getJSONObject("data")
                    val rows = data.getJSONArray("records")
                    if (success) {
                        activity!!.runOnUiThread {
                            if (rows.length() == 0) {
                                showToastLong("暂无数据...")
                            }
                            fresOrLoadSuccess(rows.length())
                            for (index in 0 until rows.length()) {
                                val item = MarketModel().apply { getModelInfo(rows.getJSONObject(index)) }
                                marketList.add(item)
                            }
//                            judgeVip()
                            marketAdapter.notifyDataSetChanged()
                        }
//                        LCLogger.d(TAG, "获取成功！,返回信息：$jsonObject")
                    } else {
                        freshOrLoadFaild()
                        LCBaseUtil.showToast(context, "获取失败，$msg")
                    }
                } catch (e: Exception) {
                    freshOrLoadFaild()
                    LCBaseUtil.showToast(context, "获取失败，" + e.message)
                    Log.e("LCLOG_ERROR", e.toString())
                }
            }
        })
    }

    private fun fresOrLoadSuccess(rows: Int) {
        if (1 == currentPage) { // 刷新
            pullRefreshLayout.refreshSuccess()
            marketList.clear()
        } else {
            pullRefreshLayout.loadmoreSuccess()
        }
        if (rows == PAGE_SIZE) {
            pullRefreshLayout.isLoadmoreable = true
        } else {
            pullRefreshLayout.isLoadmoreable = false
        }
    }

    private fun freshOrLoadFaild() {
        activity?.runOnUiThread {
            if (currentPage == 1) {
                pullRefreshLayout.refreshFailed();
            } else {
                pullRefreshLayout.loadmoreFailed()
            }
        }
    }

}